<?php
/**
 * Created by PhpStorm.
 * User: jerry
 * Date: 2018/4/12
 * Time: 15:12
 */
namespace App\Libs;

use Mockery\Exception;

class CommonUtils
{
    /**
     *  根据身份证号码获取性别 http://www.youhutong.com/index.php/article/index/154.html
     * @param string $idCard 身份证号码
     * @return int $sex 性别 1男 2女 0未知
     */
    public static function get_sex($idCard)
    {
        if (empty($idCard)) return null;
        $sexInt = (int)substr($idCard, 16, 1);
        return $sexInt % 2 === 0 ? 2 : 1;
    }

    /**
     *  根据身份证号码计算年龄
     * @param string $idCard 身份证号码
     * @return int $age
     */
    public static function get_age($idCard)
    {
        if (empty($idCard)) return null;
//        #  获得出生年月日的时间戳
//        $date = strtotime(substr($idCard, 6, 8));
//        #  获得今日的时间戳
//        $today = strtotime('today');
//        #  得到两个日期相差的大体年数
//        $diff = floor(($today - $date) / 86400 / 365);
//        #  strtotime加上这个年数后得到那日的时间戳后与今日的时间戳相比
//        $age = strtotime(substr($idCard, 6, 8) . ' +' . $diff . 'years') > $today ? ($diff + 1) : $diff;
        $year = substr($idCard, 6, 4);
        $month = substr($idCard, 10, 2);
        $day = substr($idCard, 12, 2);
        $age = date('Y') - $year;
        if ($month > date('m') || ($month == date('m') && $day > date('d'))) {
            $age--;
        }
        return $age;
    }

    /**
     *  判断字符串是否是身份证号
     * @param string $idCard 身份证号码
     * @return bool
     */
    public static function isIdCard($idCard)
    {
        #  转化为大写，如出现x
        $idCard = strtoupper($idCard);
        #  加权因子
        $wi = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
        $ai = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
        #  按顺序循环处理前17位
        $sigma = 0;
        #  提取前17位的其中一位，并将变量类型转为实数
        for ($i = 0; $i < 17; $i++) {
            $b = (int)$idCard{$i};
            #  提取相应的加权因子
            $w = $wi[$i];
            #  把从身份证号码中提取的一位数字和加权因子相乘，并累加
            $sigma += $b * $w;
        }
        #  计算序号
        $sidcard = $sigma % 11;
        #  按照序号从校验码串中提取相应的字符。
        $check_idcard = $ai[$sidcard];
        if ($idCard{17} == $check_idcard) {
            return true;
        } else {
            return false;
        }
    }

    public $chartConfig = [
        'config' => [
            'title' => [
                'text' => '',
            ],

            'tooltip' => [
                'trigger' => 'axis',
                'axisPointer' => [
                    'type' => 'cross',
                    'label' => [
                        'backgroundColor' => '#283b56'
                    ]
                ]
            ],
            'legend' => [
//                'data' => ['新增志愿者数量', '累计志愿者数量']
                'data' => [
                    [
                        'name' => '新增志愿者数量',
                        'icon' => 'circle',
                        // 设置文本为红色
                        'textStyle' => [
                            'color' => 'red'
                        ],

                    ],
                    [
                        'name' => '累计志愿者数量',
                        'icon' => 'pin',
                        'textStyle' => [
                            'color' => '#283b56'
                        ],

                    ]
                ]

            ],
            'toolbox' => [
                'show' => true,
                'feature' => [
                    'dataView' => ['readOnly' => false],
                    'restore' => [],
                    'saveAsImage' => []
                ]
            ],
            'dataZoom' => [
                'show' => false,
                'start' => 0,
                'end' => 100
            ],
            'xAxis' => [
                [
                    'type' => 'category',
                    'boundaryGap' => true,
                    'data' => ["9:59:52", "9:59:54", "9:59:56", "9:59:58", "10:00:00", "10:00:02", "10:00:04", "10:00:06", "10:00:08", "10:00:10", "10:00:12", "10:00:14", "10:00:16", "10:00:18", "10:00:20", "10:00:22", "10:00:24", "10:00:26", "10:00:28", "10:00:30"],
                ],
//                [
//                    'type' => 'category',
//                    'boundaryGap' => true,
//                    'data' => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
//                ]
            ],
            'yAxis' => [
                [
                    'type' => 'value',
                    'scale' => true,
                    'name' => '新增数量',
                    'splitLine' => [
                        'show' => true,
                        'lineStyle' => [
                            'color' => '#999',
                            'type' => 'dashed'
                        ]
                    ],
//                    'max' => 30,
//                    'min' => 0,
//                    'boundaryGap' => [0.2, 0.2]
                ],
                [
                    'type' => 'value',
                    'scale' => true,
                    'name' => '累计数量',
                    'splitLine' => [
                        'show' => true,
                        'lineStyle' => [
                            'color' => '#999',
                            'type' => 'dashed'
                        ]
                    ],
//                    'max' => 1200,
//                    'min' => 0,
//                    'boundaryGap' => [0.2, 0.2]
                ],
            ],
            'series' => [

                [
                    'name' => '新增志愿者数量',
                    'type' => 'line',
                    'data' => [14.4, 10.5, 5.3, 6.9, 8.7, 9.5, 6.4, 7.3, 5.5, 6, 7.2, 12.9, 12.5, 12.6, 7.9, 12.3, 9.7, 12.8, 6.5, 5.1]
                ],
                [
                    'name' => '累计志愿者数量',
                    'type' => 'line',
//                    'xAxisIndex' => 0,
                    'yAxisIndex' => 1,
                    'data' => [165, 411, 29, 199, 324, 235, 195, 627, 148, 254]
                ]
            ],
        ]];


    /**
     * @param array $dateRange
     * @param array $addData
     * @param array $totalData
     * @param array $label
     * @return array
     * @throws \Exception
     */
    public function userIncreaseChartConfig(array $dateRange, array $addData, array $totalData, array $label=['新增志愿者数量', '累计志愿者数量'])
    {
        if (!isset($dateRange) || !$dateRange || count($dateRange) <= 0
            || !$addData || !$totalData || count($addData) <= 0 || count($totalData) <= 0) {
            dd($dateRange, $addData, $totalData);

            throw new \Exception('内部错误');
        }
        $config = $this->chartConfig['config'];


        $config['xAxis'][0]['data'] = $dateRange;
//        $config['yAxis'][0]['max'] = max($addData);
//        $config['yAxis'][0]['min'] = min($addData);
//        $config['yAxis'][1]['max'] = max($totalData);
//        $config['yAxis'][1]['min'] = min($totalData);
        $config['series'][0]['data'] = $addData;
        $config['series'][0]['name'] = $label[0];
        $config['legend']['data'][0]['name'] = $label[0];
        $config['legend']['data'][1]['name'] = $label[1];

        $config['series'][1]['data'] = $totalData;
        $config['series'][1]['name'] = $label[1];

        return $config;
    }

    public static function userGenderChartConfig(array $genderData)
    {
        if (!$genderData || count($genderData) != 3) {
            throw new \Exception('参数错误');
        }
        $config = '{"title":{"text":"","subtext":""},"tooltip":{"trigger":"axis","axisPointer":{"type":"cross"}},"legend":{"data":["男","女","未知"],"position":"bottom"},"grid":{"left":"0%","right":"4%","bottom":"3%","containLabel":true},"xAxis":[{"type":"value","splitLine":{"show":true,"lineStyle":{"color":"#999","type":"dashed"}}}],"yAxis":[{"type":"category","axisTick":{"show":false},"data":["性别"]}],"series":[{"name":"男","type":"bar","stack":"总量","barMinHeight":50,"barWidth":40,"barMaxWidth":40,"itemStyle":{"normal":{"color":"#5ab1ef","label":{"show":true,"position":"bottom","textStyle":{"color":"#000","fontSize":"15"}}}},"data":[320]},{"name":"女","type":"bar","stack":"总量","barMinHeight":80,"barWidth":40,"barMaxWidth":40,"itemStyle":{"normal":{"color":"#d87a80","label":{"show":true,"position":"bottom","textStyle":{"color":"#000","fontSize":"15"}}}},"data":[120]},{"name":"未知","type":"bar","stack":"总量","barMinHeight":50,"barWidth":40,"barMaxWidth":40,"itemStyle":{"normal":{"color":"#ffb980","label":{"show":true,"position":"bottom","textStyle":{"color":"#000","fontSize":"15"}}}},"data":[281]}]}';
        try {
            $config = json_decode($config);
        } catch (Exception $e) {
            throw new Exception ($e->getMessage());
        }
//        dd($config);

        $config->series[0]->data = array($genderData[1]);  // 男
        $config->series[1]->data = array($genderData[0]);  // 女
        $config->series[2]->data = array($genderData[2]);  // 未知
        return $config;

    }

    public static function userAgeChartConfig(array $ageData, array $label= [ '20岁以下','20~29岁','30~39岁','40~49岁','50岁以上']) {
        $config = '{"title":{"text":"","subtext":"","x":"center"},"tooltip":{"trigger":"item","formatter":"{a} <br/>{b} : {c} ({d}%)"},"legend":{"type":"scroll","orient":"vertical","right":10,"top":20,"bottom":20,"data":["20岁以下","20~29岁","30~39岁","40~49岁","50岁以上"]},"series":[{"name":"年龄段","type":"pie","radius":"65%","center":["40%","50%"],"label":{"show":true,"formatter":"{b}\n占{d}%"},"data":[{"name":"20岁以下","value":1000},{"name":"20~29岁","value":1000},{"name":"30~39岁","value":1000},{"name":"40~49岁","value":1000},{"name":"50岁以上","value":1000}],"itemStyle":{"emphasis":{"shadowBlur":10,"shadowOffsetX":0,"shadowColor":"rgba(0, 0, 0, 0.5)"}}}],"color":["#2ec7c9","#b6a2de","#5ab1ef","#ffb980","#d87a80","#8d98b3","#e5cf0d","#97b552","#95706d","#dc69aa","#07a2a4","#9a7fd1","#588dd5","#f5994e","#c05050","#59678c","#c9ab00","#7eb00a","#6f5553","#c14089"]}';
        try {
            $config = json_decode($config);
        } catch (Exception $e) {
            throw new Exception ($e->getMessage());
        }
        $config->series[0]->data = $ageData;
        $config->legend->data = $label;
        return $config;
    }

    public static function userAreaChartConfig(array $areaData, $max, array $label=['志愿者数量']) {
        $config = '{"title":{"text":"","subtext":"","left":"center"},"tooltip":{"trigger":"item"},"visualMap":{"min":0,"max":2500,"left":"left","itemWidth":20,"itemHeight":180,"top":"80%","orient":"horizontal","symbol":"","type":"continuous","text":["高","低"],"realtime":false,"calculable":true,"color":["orangered","yellow","lightskyblue"]},"toolbox":{"show":true,"orient":"vertical","left":"right","top":"center","feature":{"mark":{"show":true},"dataView":{"show":true,"readOnly":false},"restore":{"show":true},"saveAsImage":{"show":true}}},"series":[{"name":"志愿者数量","type":"map","mapType":"china","roam":false,"left":"10%","top":"5%","label":{"normal":{"show":false},"emphasis":{"show":true}},"data":[]}]}';
        try {
            $config = json_decode($config);
        } catch (Exception $e) {
            throw new Exception ($e->getMessage());
        }
        $config->series[0]->data = $areaData;
        $config->visualMap->max = $max ? $max : 10;
        $config->series[0]->name = $label[0];
        return $config;
    }

    public static function teamTypeChartConfig(array $data, array $xAxisLabel, array $yAxisLabel=['团队数量'], array $color=['#339ca8']) {
        $config = '{"title":{"text":"","subtext":""},"tooltip":{"trigger":"axis","axisPointer":{"type":"cross","label":{"backgroundColor":"#283b56"}}},"toolbox":{"show":true,"feature":{"dataView":{"readOnly":false},"restore":{},"saveAsImage":{}}},"dataZoom":{"show":false,"start":0,"end":100},"xAxis":[{"type":"category","axisTick":{"alignWithLabel": true},"boundaryGap":true,"axisLabel":{"interval":1},"data":["20以下","20~29","30~39","40~49","50-59","60以上"]}],"yAxis":[{"type":"value","scale":true,"name":"团队数量","splitLine":{"show":true,"lineStyle":{"color":"#999","type":"dashed"}}}],"series":[{"name":"团队数量","type":"bar","barWidth":40,"barMaxWidth":40,"itemStyle":{"normal":{"color":"#339ca8","label":{"show":false,"position":"bottom","textStyle":{"color":"#000","fontSize":"15"}}}},"data":[480,385,328,31,317,483,94,125,227,346]}],"color":["#c12e34","#e6b600","#0098d9","#2b821d","#005eaa","#339ca8","#cda819","#32a487"]}';
        try {
            $config = json_decode($config);
        } catch (Exception $e) {
            throw new Exception ($e->getMessage());
        }
        $config->series[0]->data = $data;
        $config->xAxis[0]->data = $xAxisLabel;
        $config->yAxis[0]->name = $yAxisLabel[0];
        $config->series[0]->name = $yAxisLabel[0];
        $config->series[0]->itemStyle->normal->color = $color[0];
        return $config;
    }
}
